package com.hg.util;

import com.hg.common.enums.ResultEnum;
import com.hg.common.exception.BizException;
import com.hg.common.exception.ParamException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.FieldError;

import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import java.util.Set;

/**
 * Validate校验工具类
 * Created by skh on 2018/1/11
 */
@Component
@Slf4j
public class ValidateUtil {

	public static Validator validator;

	public static <T> void validate(T t) {
		Set<ConstraintViolation<T>> constraintViolations = validator.validate(t);
		if (CollectionUtils.isNotEmpty(constraintViolations)) {
			//拼接错误信息
			StringBuilder sb = new StringBuilder();
			for (ConstraintViolation<T> constraintViolation : constraintViolations) {
				sb.append(constraintViolation.getMessage()).append(",");
			}
			String errorMsg = sb.substring(0, sb.length() - 1).toString();
			log.error("校验{}发生参数异常:{}", t, errorMsg);
			throw new ParamException(ResultEnum.PARAM_ERROR.getCode(), errorMsg);
		}

	}

	@Autowired
	public void setValidator(Validator validator) {
		ValidateUtil.validator = validator;
	}
}
